package com.example.wait;

public class studyWait {

    public static void main(String[] args) {
        Object lock = new Object();
        Object wlock = new Object();
        WaitThread w1 = new WaitThread(lock, "线程1");
        w1.start();
/*        Object wlock2 = new Object();
        WaitThread w2 = new WaitThread(lock,"s线程2");
        w2.start();*/
        NotifyThread t2 = new NotifyThread(lock, "线程2");
        t2.start();
    }
}
class WaitThread extends Thread {
    private final Object lock;
    private String name;

    public WaitThread(Object lock, String name) {
        super();
        this.lock = lock;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {//同步代码块
                long start = System.currentTimeMillis();
                System.out.println(name + "开始 wait time= " + start);
                Thread.sleep(3000);
                System.out.println(name + "wait 休眠 3000ms");
                lock.wait();
                System.out.println("等待……");
                long end = System.currentTimeMillis();
                System.out.println(name + "结束 wait time= " + end);
                System.out.print(name + "wait time = " + (end - start));
            }
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
class NotifyThread extends Thread {
    private final Object lock;
    private String name;

    public NotifyThread(Object lock, String name) {
        super();
        this.lock = lock;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (lock) {
            // 业务逻辑完成了...
            System.out.println(name + "开始 notify time= " + System.currentTimeMillis());
            // 做一些业务逻辑相关的事。。。。
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            lock.notifyAll();//刷新全部
            System.out.println(name + "结束 notify time= " + System.currentTimeMillis());
        }
    }
}



